<?php
namespace Api\Controller;

use Overtrue\Socialite\SocialiteManager;

class AuthController extends  BaseController {

    private $socialite;
    private $auth_config;

    public function _initialize() {
        // parent::_initialize();
        $config = C('qq');

        $callback = isset($_GET['callback']) ? $_GET['callback'] : '';
        $token = isset($_GET['token']) ? $_GET['token'] : '';

        if($callback){
            cookie('callback', $callback);
            cookie('token', $token);
        }
        $this->auth_config = [
            'qq'    => [
                'client_id'     => $config['web_appid'],
                'client_secret' => $config['web_appkey'],
                'redirect'      => U('auth/auth_callback', ['driver'=>'qq'], true, true),
            ],
        ];
        require_once VENDOR_PATH.'autoload.php';
        $this->socialite = new SocialiteManager($this->auth_config);
    }


    public function auth($driver)
    {
        $with = [];
        if(isMobile()){
            $with['display'] = 'mobile';
        }
        $response = $this->socialite->driver($driver)->with($with)->redirect();
        $response->send();
    }

    public function auth_callback($driver)
    {
        $callback = empty(cookie('callback')) ? '' : cookie('callback');
        $token = empty(cookie('token')) ? '' : cookie('token');
        try{
            $user = $this->socialite->driver($driver)->withUnionId()->user();
            $userInfo = $user->toArray();
            if($userInfo){
                switch ($userInfo['provider']) {
                    case 'QQ':
                        if($token){
                            $user = M('user')->where(['cid'=>$token])->find();
                            if(empty($user)){
                                $user = M('token')->where(['token'=>$token])->find();
                                if($user){
                                    $user['id'] = $user['uid'];
                                }
                            }
                        }
                        if(!empty($user['id'])){
                            $data = [
                                'qqnickname'    => $userInfo['original']['nickname'],
                                'qqwebopenid'   => $userInfo['id'],
                                'qqunionid'     => $userInfo['unionid'],
                            ];
                            $res = M('user')->where(array('id'=>$user['id']))->data($data)->save();
                        }
                        break;
                    default:
                        break;
                }
            }
        }catch(\Exception $e){
            $msg = $e->getmessage();
        }
        $callback && redirect($callback);
    }
}